package cn.sczc.jh.client.service.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.sczc.jh.client.entity.Permission;
import cn.sczc.jh.client.entity.Role;
import cn.sczc.jh.client.entity.Teams;
import cn.sczc.jh.client.entity.User;
import cn.sczc.jh.client.entity.UserRoleRef;
import cn.sczc.jh.client.exception.BusinessException;
import cn.sczc.jh.client.mapper.sys.RoleMapper;
import cn.sczc.jh.client.mapper.sys.UserMapper;
import cn.sczc.jh.client.service.team.TeamService;
import cn.sczc.jh.client.vo.UserVo;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService extends ServiceImpl<UserMapper, User>{

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private TeamService teamService;

	@Autowired
	private PermissionService permissionService;

	public Page<UserVo> getUserByParams(Page<UserVo> page, Map<String, Object> params) {
		List<UserVo> list = userMapper.getUserByParams(page, params);
		page.setRecords(list);
		return page;
	}

	public int addUser(UserVo user) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("username_", user.getUsername());
		int count = userMapper.selectCount(wrapper);
		if (count > 0) {
			throw new BusinessException("用户已存在！");
		} else {
			user.setId(IdWorker.getId());
//			user.setCreateBy(WebUtil.getCurrentUser());
			user.setCreateTime(new Date());
			if (user.getRoleIds() != null) {
				String[] roleIdArray = user.getRoleIds().split(",");
				if (roleIdArray != null && roleIdArray.length > 0) {
					List<Long> roleIdList = new ArrayList<>();
					for (String roleId : roleIdArray) {
						roleIdList.add(Long.valueOf(roleId));
					}
					this.batchAddUserRoleRef(roleIdList, user.getId());
				}
			}
			return userMapper.insert(user);
		}
	}

	public void batchAddUserRoleRef(List<Long> roleIds, Long userId) {
		List<UserRoleRef> userRoleRefList = new ArrayList<>();
		for (Long roleId : roleIds) {
			UserRoleRef userRoleRef = new UserRoleRef();
			userRoleRef.setId(IdWorker.getId());
			userRoleRef.setUserId(userId);
			userRoleRef.setRoleId(roleId);
			userRoleRef.setCreateTime(new Date());
//			userRoleRef.setCreateBy(WebUtil.getCurrentUser());
			userRoleRefList.add(userRoleRef);
		}
		userMapper.batchAddUserRoleRef(userRoleRefList);
	}

	public int updateUser(UserVo user) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.ne("id_", user.getId());
		wrapper.eq("username_", user.getUsername());
		int count = userMapper.selectCount(wrapper);
		if (count > 0) {
			throw new BusinessException("用户已存在！");
		} else {
			// user.setUpdateBy(WebUtil.getCurrentUser());
			// 删除用户角色表
			this.removeUserRoleRef(user.getId());
			user.setUpdateTime(new Date());
			if (user.getRoleIds() != null) {
				String[] roleIdArray = user.getRoleIds().split(",");
				if (roleIdArray != null && roleIdArray.length > 0) {
					List<Long> roleIdList = new ArrayList<>();
					for (String roleId : roleIdArray) {
						roleIdList.add(Long.valueOf(roleId));
					}
					this.batchAddUserRoleRef(roleIdList, user.getId());
				}
			}
			return userMapper.updateById(user);
		}
	}

	private int removeUserRoleRef(Long userId) {
		return userMapper.removeUserRoleRef(userId);
	}

	public int delById(Long id) {
		userMapper.removeUserRoleRef(id);
		return userMapper.deleteById(id);
	}

	public User getUserInfo(Long id) {
		return userMapper.selectById(id);
	}

	public UserVo getUser(String username, String password) {
		return userMapper.getUser(username, password);
	}

	public User getUserByAccount(String userName) {
		User user = userMapper.getUserByAccount(userName);
		if (user != null) {
			List<Role> roleList = roleMapper.getRoleListByUserId(user.getId());
			user.setRoles(roleList);
			List<Permission> permissionList = permissionService.getPermissionByUserId(user.getId());
			user.setPermissions(permissionList);
			List<Teams> teamList = teamService.selectListByTenantId(user.getTenantId());
			user.setTeams(teamList);
		}
		return user;
	}

}
